package edu.cnu.tpts.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 功能描述：用于管理数据库打开（获得数据库连接）和关闭
 * 
 */
public class DBManager {
	/**
	 * 封装数据集库连接实例
	 */
	private Connection conn;  //数据库连接
	private String driver="com.mysql.jdbc.Driver"; //数据库驱动字符串
	private String url= "jdbc:mysql://localhost:3306/tpts"; //URL
	private String userName= "root"; //用户名
	private String password= "root";//密码

	/**
	 * 获得数据库连接对象
	 * 
	 * @return conn 数据库连接对象
	 */
	public Connection getConnection() {
		try {
			Class.forName(driver).newInstance();
			conn = DriverManager.getConnection(url, userName, password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 关闭数据库
	 * 
	 * @param rs
	 *            记录集对象
	 * @param pstmt
	 *            批处理对象
	 * @param conn
	 *            数据库连接对象
	 */
	public void closeAll(ResultSet rs, Statement stmt, Connection conn) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		DBManager dBManager=new DBManager();
		Connection conn= dBManager.getConnection();
		dBManager.closeAll(null, null, conn);
		
	}
}
